﻿CREATE TRIGGER tr_Income_OfInsert
ON dbo.t_Income
INSTEAD OF INSERT
AS

IF EXISTS(SELECT * FROM inserted WHERE (LTRIM(Name) = '' OR ISNULL(Value,0) = 0) AND Pos > (SELECT COUNT(*) FROM ts_IncomeType))BEGIN
	DELETE t_Income FROM t_Income inc
	INNER JOIN inserted i
	ON inc.BorrowerID = i.BorrowerID AND inc.Pos = i.Pos
	RETURN -->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
END


UPDATE t_Income
SET Name = i.Name,Value = i.Value
FROM t_Income inc INNER JOIN inserted i
ON inc.BorrowerID = i.BorrowerID AND inc.Pos = i.Pos

IF @@ROWCOUNT > 0 RETURN

DECLARE @BorrID int,@Pos int,@PosMax int

SELECT @BorrID = BorrowerID,@Pos = NULLIF(Pos,0) FROM inserted

SELECT @PosMax = MAX(inc.Pos) FROM t_Income inc INNER JOIN inserted i
ON inc.BorrowerID = i.BorrowerID

SET @Pos = dbo.MinNum(@Pos,ISNULL(@PosMax+1,0))

PRINT 'BorrowerID:'+STR(@BorrID)

INSERT INTO t_Income SELECT BorrowerID,ISNULL(NULLIF(Pos,0),@Pos),Name,Value FROM inserted
